package com.byq.mcpanus.service;

import com.byq.mcpanus.model.Conversation;
import com.byq.mcpanus.model.MyConversation;
import com.byq.mcpanus.repository.MyConversationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ConversationService {
    @Autowired
    private MyConversationRepository myConversationRepository;

    public Conversation getConversation(String id) {
        Optional<MyConversation> rst = myConversationRepository.findById(id);
        return rst.map(MyConversation::toConversation).orElse(null);
    }

    @Transactional
    public void save(Conversation con) {
        MyConversation my = new MyConversation();
        my.fromConversation(con);
        myConversationRepository.save(my);
    }

    public List<Conversation> getAll() {
        List<MyConversation> ls = myConversationRepository.findAll();
        List<Conversation> rst = new ArrayList<>();
        for (MyConversation m : ls) {
            Conversation con = m.toConversation();
            rst.add(con);
        }
        return rst;
    }
}
